<template>
  <div class="product-list">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>产品管理</span>
          <el-button type="primary" @click="addProduct">新增产品</el-button>
        </div>
      </template>

      <el-form :model="queryParams" label-width="100px" style="margin-bottom: 20px;">
        <el-row :gutter="20">
          <el-col :span="6">
            <el-form-item label="产品名称">
              <el-input v-model="queryParams.name" clearable />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="产品编码">
              <el-input v-model="queryParams.code" clearable />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="状态">
              <el-select v-model="queryParams.status" placeholder="请选择" style="width: 100%">
                <el-option label="全部" :value="null" />
                <el-option label="上架" :value="1" />
                <el-option label="下架" :value="0" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-button type="primary" @click="search">搜索</el-button>
            <el-button @click="reset">重置</el-button>
          </el-col>
        </el-row>
      </el-form>

      <el-table :data="products" border style="width: 100%">
        <el-table-column prop="id" label="ID" width="50"/>
        <el-table-column prop="name" label="产品名称"/>
        <el-table-column prop="code" label="产品编码"/>
        <el-table-column prop="unit" label="单位"/>
        <el-table-column prop="purchase_price" label="采购价">
          <template #default="{ row }">
            ￥{{ formatPrice(row.purchase_price) }}
          </template>
        </el-table-column>
        <el-table-column prop="sale_price" label="销售价">
          <template #default="{ row }">
            ￥{{ formatPrice(row.sale_price) }}
          </template>
        </el-table-column>
        <el-table-column prop="stock" label="库存"/>
        <el-table-column prop="warning_stock" label="预警库存">
          <template #default="{ row }">
            <span :class="{ 'text-danger': row.stock <= row.warning_stock }">
              {{ row.warning_stock }}
            </span>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态">
          <template #default="{ row }">
            <el-tag :type="row.status === 1 ? 'success' : 'danger'">
              {{ statusMap[row.status] }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200">
          <template #default="{ row }">
            <el-button size="small" @click="editProduct(row)">编辑</el-button>
            <el-button size="small" type="danger" @click="deleteProduct(row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <el-pagination
          v-model:current-page="queryParams.page"
          v-model:page-size="queryParams.size"
          :total="total"
          @current-change="getList"
          layout="prev, pager, next"
          style="margin-top: 20px;"
      />
    </el-card>

    <!-- 新增/编辑弹窗 -->
    <el-dialog v-model="dialogVisible" :title="isEdit ? '编辑产品' : '新增产品'" width="50%">
      <el-form ref="formRef" :model="formData" label-width="120px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="产品名称">
              <el-input v-model="formData.name"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="产品编码">
              <el-input v-model="formData.code"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="单位">
              <el-input v-model="formData.unit"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="采购价">
              <el-input-number v-model="formData.purchase_price" :precision="2" :step="0.1" style="width: 100%"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="销售价">
              <el-input-number v-model="formData.sale_price" :precision="2" :step="0.1" style="width: 100%"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="预警库存">
              <el-input-number v-model="formData.warning_stock" :step="1" style="width: 100%"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="状态">
              <el-select v-model="formData.status" placeholder="请选择" style="width: 100%">
                <el-option label="上架" :value="1"/>
                <el-option label="下架" :value="0"/>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item>
          <el-button type="primary" @click="saveProduct">保存</el-button>
          <el-button @click="dialogVisible = false">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script setup>
import {ref, onMounted} from 'vue'
import request from '@/utils/request'
import { ElMessage } from 'element-plus'

const products = ref([])
const total = ref(0)
const queryParams = ref({
  page: 1,
  size: 10,
  name: '',
  code: '',
  status: null
})

const statusMap = {
  0: '下架',
  1: '上架'
}

const dialogVisible = ref(false)
const isEdit = ref(false)
const formData = ref({
  id: null,
  name: '',
  code: '',
  unit: '',
  purchase_price: 0,
  sale_price: 0,
  warning_stock: 0,
  status: 1
})

const formRef = ref(null)

const formatPrice = (price) => {
  return parseFloat(price).toFixed(2)
}

const getList = async () => {
  try {
    const res = await request.get('/product/', {params: queryParams.value})
    products.value = res.records
    total.value = res.total
  } catch (error) {
    console.error('获取产品列表失败:', error)
  }
}

const addProduct = () => {
  isEdit.value = false
  formData.value = {
    name: '',
    code: '',
    unit: '',
    purchase_price: 0,
    sale_price: 0,
    warning_stock: 0,
    status: 1
  }
  dialogVisible.value = true
}

const editProduct = (row) => {
  isEdit.value = true
  formData.value = {...row}
  dialogVisible.value = true
}

const deleteProduct = async (id) => {
  try {
    await request.delete(`/product/${id}/`)
    ElMessage.success('删除成功')
    getList()
  } catch (error) {
    ElMessage.error('删除失败')
  }
}

const saveProduct = async () => {
  try {
    if (isEdit.value) {
      // 编辑
      const res = await request.put(`/product/${formData.value.id}/`, formData.value)
      ElMessage.success('更新成功')
    } else {
      // 新增
      const res = await request.post('/product/', formData.value)
      ElMessage.success('创建成功')
    }
    dialogVisible.value = false
    getList()
  } catch (error) {
    ElMessage.error('操作失败')
  }
}

const search = () => {
  queryParams.value.page = 1
  getList()
}

const reset = () => {
  queryParams.value = {
    page: 1,
    size: 10,
    name: '',
    code: '',
    status: null
  }
  getList()
}

onMounted(() => {
  getList()
})
</script>

<style scoped>
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
</style>
